//
//  OAuthUIViewController.swift
//  weibo09
//
//  Created by Jet on 16/5/7.
//  Copyright © 2016年 Jet. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthUIViewController: UIViewController {

    //填写密码
    let value = ""
    
    //定义一个webView/　SFSafariViewController
    let webView = UIWebView()
    
    override func loadView() {
        view = webView
    }
    
   @objc private func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fullAccount(){
        let jsString = "document.getElementById('userId').value = '江建涛',document.getElementById('passwd').value = '\(value)';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        setupUI()
        //2.加载网络授权页
        loadOauthPage()
        // Do any additional setup after loading the view.
    }
    
    func setupUI(){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        //自动填充按钮
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    
    
    func loadOauthPage(){
      
        let urlString = "https://api.weibo.com/oauth2/authorize?"+"client_id="+client_id+"&redirect_uri="+redirect_uri
       // print(urlString)
        let request = NSURLRequest(URL: NSURL(string: urlString)!)
        webView.loadRequest(request)
    }
}

extension OAuthUIViewController:UIWebViewDelegate{

    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //返回true表示允许正常加载请求/false则不允许加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
     //３.网络拦截，获取到正确的动态密令code
        //检测url是否为空，空则不通过
        guard let urlString = request.URL?.absoluteString else{
        
            return false
        }
        
        //检测为API请求则通过
        if urlString.hasPrefix("https://api.weibo.com"){
        
            return true
        }
       
        if !urlString.hasPrefix(redirect_uri){
        
            return false
        }
        
        guard let query = request.URL?.query else{
        
            return false
        }
        //获取到正确的动态密令code
        let code = query.substringFromIndex("code=".endIndex)
        //４.根据code请求用户令牌token,请求结束回调
        UserAccountViewModel().loadAccessToken(code) { (error) in
         self.dismissViewControllerAnimated(true, completion: nil)
        }
        return true
    }
    
  }


